package myself.study.network.tcp.demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import org.junit.Test;

/**
* @Name: TcpClient
* @Description: tcp协议通信客户端
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-1-12 下午12:53:17 
* @Version: V1.0
 */
public class TcpClient {
	
	@Test
	public void clientTest() throws UnknownHostException, IOException {
		//创建客户端Socket对象
		Socket client = new Socket("127.0.0.1", 12345) ;
		//获取输出流对象，向服务端发送请求数据
		OutputStream outputStream = client.getOutputStream() ;
		String requestData = "hello,tcp,我来了!" ;
		outputStream.write(requestData.getBytes()) ;
		System.out.println("to server : " + requestData);
		//获取输入流对象，获取服务端响应结果
		InputStream inputStream = client.getInputStream() ;
		byte[] buf = new byte[1024] ;
		int len = inputStream.read(buf) ;  //阻塞3
		String responseData = new String(buf, 0, len) ;
		System.out.println("from server : " + responseData);
		//释放资源
		client.close() ;
	}

}
